export default {
	config: {
		baseUrl: "https://api.bytesbay.cn",
		header: {
			Token: uni.getStorageSync('bytesbayToken')
		},
		dataType: "json",
		responseType: "text"
	},
	interceptor: {
		request: null,
		response: null
	},
	request(options) {
		return new Promise((resolve, reject) => {
			let _config = null
			options.url = this.config.baseUrl + options.url
			this.config.header.Token = uni.getStorageSync('bytesbayToken')
			options.complete = (response) => {
				let statusCode = response.statusCode

				response.config = _config

				if (process.env.NODE_ENV === 'development') {
					if (statusCode === 200) {
						// console.log("【" + _config.requestId + "】 结果：" + JSON.stringify(response.data))
					}
				}

				if (this.interceptor.response) {
					let newResponse = this.interceptor.response(response.data)
					if (newResponse) {
						response = newResponse
					}
				}

				if (statusCode === 200) { //成功
					if (response.data.is_alert) { 
						setTimeout(() => {
							uni.showToast({
								icon: 'none',
								title: response.data.msg,
								duration: 2500
							})
						}, 100)
					}
					if (response.data.code == 1008) {
						uni.setStorageSync('bytesbayToken', '')
						uni.setStorageSync('userinfo', JSON.stringify({}))
					}
					// if (response.data.code == 1000 || response.data.code == 1008) {
					// 	resolve(response.data);
					// } else { 
					// 	resolve(response.data)
					// }
					resolve(response.data)
				} else {
					reject(response.data)
				}
			}
				
			_config = Object.assign({}, this.config, options)
			_config.requestId = new Date().getTime()

			if (this.interceptor.request) {
				this.interceptor.request(_config)
			}

			if (process.env.NODE_ENV === 'development') {
				// console.log("【" + _config.requestId + "】 地址：" + _config.url)
				if (_config.data) {
					// console.log("【" + _config.requestId + "】 参数：" + JSON.stringify(_config.data))
				}
			}
			// console.log('--------request----------', _config)
			uni.request(_config);
		});
	},
	get(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'GET'
		return this.request(options)
	},
	post(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	},
	put(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'PUT'
		return this.request(options)
	},
	delete(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return this.request(options)
	}
}
